package com.example.gfsquadwebviewproject.util;

import android.content.Context;
import android.os.CountDownTimer;
import android.view.MotionEvent;

public class MyCountDownTimer {

    public CountDownTimer countDownTimer;
    private long advertisingTime;//定时跳转广告时间
    public Context context;

    ICountDownCallback iCountDownCallback;

    public MyCountDownTimer(Context context,ICountDownCallback iCountDownCallback,long advertisingTime) {
        this.context = context;
        this.iCountDownCallback = iCountDownCallback;
        this.advertisingTime = (advertisingTime*1000)+300;
    }


    public void dispatchTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                //有按下动作时取消定时
                if (countDownTimer != null){
                    countDownTimer.cancel();
                }
                break;
            case MotionEvent.ACTION_UP:
                //抬起时启动定时
                start();
                break;
        }
    }


    /**
     * 跳轉廣告
     */
    public void start() {
        if (countDownTimer == null) {
            countDownTimer = new CountDownTimer(advertisingTime, 1000l) {
                @Override
                public void onTick(long millisUntilFinished) {
                    iCountDownCallback.onTimeTick((int)(millisUntilFinished/1000));
                }

                @Override
                public void onFinish() {
                    iCountDownCallback.onTimeOut();
                }
            };
            countDownTimer.start();
        } else {
            countDownTimer.start();
        }
    }


    public void stop(){
        if (countDownTimer != null){
            countDownTimer.cancel();
        }
    }

    public interface ICountDownCallback{
        void onTimeTick(int second);

        void onTimeOut();
    }

}
